package com.springboot.middleware.middleware_grab_red_envelopes.server.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class RedPacketUtil {
    /**
     * 发红包算法,金额参数以分为单位
     *
     * @param totalAmount    红包总金额,单位:分
     * @param totalPeopleNum 总人数
     * @return 每次产生的小红包的随机金额的List, 单位为分
     */
    public static List<Integer> divideRedPackage(Integer totalAmount, Integer totalPeopleNum) {
        List<Integer> amountList = new ArrayList<>();
        //合法性检查
        if (totalAmount > 0 && totalPeopleNum > 0) {
            //记录剩余的总金额
            Integer restAmount = totalAmount;
            //记录剩余的总人数
            Integer restPeopleNum = totalPeopleNum;
            Random random = new Random();
            //不断更新产生随机金额,直到剩余人数-1>0不满足
            for (int i = 0; i < totalPeopleNum - 1; i++) {
                //随机范围: [1,剩余人均金额的2倍) ,单位:分
                int amount = random.nextInt(restAmount / restPeopleNum * 2 - 1) + 1;
                restAmount -= amount;
                restPeopleNum--;
                amountList.add(amount);
            }
            //循环完毕,剩余的金额为最后一个随机金额
            amountList.add(restAmount);
        }

        return amountList;
    }
}
